// pages/register/register.js
const { Util } = require('../../utils/util');
const wxapi = require('../../utils/wxapi');
const { API_UC_URL } = require('../../utils/wxapi');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneCode: null,
    contactsMsg: null,
    idTypeIndex: 0,
    idTypeTypeArray: ['身份证', '港、澳身份证', '护照'],
    sex: 0,
    sexOfData: ['男', '女'],
    birthday: null,
    memberFormValid: true,
    userPhoneValid: true,
    idCardValid: true,
    errMsg: {},
    requireKey: ['nickName', 'userPhone', 'certificateNo', 'addressDetail', 'email', 'region'],
    collapsed: false,
    fatherStk: null,
    phoneNum: '',
    region: null,
    customItem: '全部',
    showPhonecode: false,
    areaMsg: null,
    isFlag: false,
    registerMsg: null,
    isSubmit: false,
    showResult: false,
    cardNo: ''
  },

  /**
   * 注册用户
   */
  submitRegister(e) {
    if (this.data.isFlag) { return; }
    this.setData({
      isFlag: true
    })
    const formData = e.detail.value;
    for (const key in formData) {
      if (Object.hasOwnProperty.call(formData, key)) {
        const formItem = formData[key];
        const requireIndex = this.data.requireKey.findIndex(item => item === key);
        if (requireIndex !== -1 && (!formItem || formItem.length === 0)) {
          this.data.memberFormValid = false;
          break;
        } else {
          this.data.memberFormValid = true;
        }
      }
    }
    if (!this.data.memberFormValid || !this.data.userPhoneValid || !this.data.idCardValid) {
      wx.showToast({
        title: '请填写正确信息',
        duration: 2000,
        success: () => {
          this.setData({
            isFlag: false
          })
        }
      })
      return;
    }
    const registerMsg = Object.assign(formData, { sex: this.data.sex, birthday: this.data.birthday })
    this.setData({
      showPhonecode: true,
      phoneNum: formData.userPhone,
      registerMsg
    })

  },

  /**
   * 验证验证码 并注册
   * @param {*} e 
   */
  checkPhoneCode(e) {
    if (this.data.isSubmit) { return; };
    this.data.isSubmit = true;
    wx.showLoading({
      title: '注册中...',
    })
    const code = e.detail.smsCode;
    const bodyParams = {
      ...this.data.registerMsg,
      ...this.data.areaMsg,
      appUserType: 0,
      channel: '神通艺术',
      code
    }
    wxapi.ValidateAddUser(bodyParams).then(res => {
      if (res.code === 20000) {
        this.setData({
          cardNo: res.data.cardNo
        })
        if (this.data.fatherStk) {
          this.addTuiGuang();
        } else {
          wx.hideLoading()
          this.setData({
            showPhonecode: false,
            phoneNum: '',
            isSubmit: false,
            isFlag: false,
            showResult: true
          })
        }

      } else {
        wx.showModal({
          title: '提示信息',
          content: res.message,
          showCancel: false
        })
      }
    })
  },

  /**
   * 关联推广人
   */
  addTuiGuang() {
    const bodyParams = {
      fatherStk: this.data.fatherStk,
      sonStk: this.data.cardNo,
      promoteType: '2'
    }
    wxapi.promoteUser(bodyParams).then(res => {
      wx.hideLoading()
      if (res.code === 20000) {
        this.setData({
          showPhonecode: false,
          phoneNum: '',
          isSubmit: false,
          isFlag: false,
          showResult: true
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.message,
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              this.cancelPopup();
            }
          }
        })
      }
    })
  },

  /**
   * 确认登录
   */
  confirmLogin() {
    this.setData({
      showResult: false,
      cardNo: ''
    })
    wx.navigateTo({
      url: `/pages/login/login`,
    })
  },

  /**
   * 取消弹窗
   * @param {*} e 
   */
  cancelPopup() {
    this.setData({
      showPhonecode: false,
      phoneNum: '',
      isSubmit: false,
      isFlag: false
    })
  },

  /**
   * 显示隐藏非必填项
   */
  toggledCollapsed() {
    this.setData({
      collapsed: !this.data.collapsed
    })
  },

  /**
     * 切换证件类型
     * @param {*} e 
     */
  bindIdTypeChange(e) {
    this.setData({
      idTypeIndex: e.detail.value
    })
  },

  /**
   * 选择日期
   * @param {*} e 
   */
  bindDateChange(e) {
    this.setData({
      birthday: e.detail.value
    })
  },

  /**
   * 地区切换
   * @param {*} e 
   */
  bindRegionChange: function (e) {
    const areaValue = e.detail.value;
    this.setData({
      region: areaValue,
      areaMsg: { belongProvince: areaValue[0], belongCity: areaValue[1], belongArea: areaValue[2] }
    })
  },

  /**
   * 根据身份证判断 出生日期 性别
   */
  idCardChange(e) {
    const userIdCard = e.detail.value;
    if (this.data.idTypeTypeArray[this.data.idTypeIndex] === '身份证') {
      const cerNoRxp = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
      if (!cerNoRxp.test(userIdCard)) {
        this.setData({
          idCardValid: false
        })
      } else {
        const birthday = Util.getBirth(userIdCard);
        const sex = Util.getSex(userIdCard);
        this.setData({
          birthday,
          sex,
          idCardValid: true
        })
      }
    }
  },

  /**
   * 验证手机号
   * @param {*} e 
   */
  checkPhone(e) {
    const phoneValue = e.detail.value;
    const phoneExg = /^1[3-9]\d{9}$/;
    if (!phoneExg.test(phoneValue)) {
      this.setData({
        userPhoneValid: false
      })
    } else {
      this.setData({
        userPhoneValid: true
      })
    }
  },

  /**
   * 初始化数据
   */
  initData() {
    this.setData({
      phoneCode: null,
      contactsMsg: null,
      idTypeIndex: 0,
      sex: 0,
      cultureIndex: null,
      birthday: null,
      memberFormValid: true,
      userPhoneValid: true,
      idCardValid: true,
      userAvatar: null,
      errMsg: {},
      collapsed: false,
      phoneNum: '',
      region: null,
      showPhonecode: false,
      isFlag: false,
      registerMsg: null,
      isSubmit: false,
      showResult: false,
      cardNo: ''
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.stk) {
      this.setData({
        fatherStk: options.stk
      })
      this.initData();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})